﻿namespace Huayou.Utils
{
    using System;
    using System.Collections;
    using System.Text;

    public class TemplateEngine
    {
        private Hashtable hs;
        private string m_content;

        public TemplateEngine(string tempfile) : this(tempfile, "gb2312")
        {
        }

        public TemplateEngine(string tempfile, string encoding)
        {
            this.hs = new Hashtable();
            this.m_content = null;
            this.m_content = FileUtils.GetContent(tempfile, encoding);
        }

        public void Replace(string before, string after)
        {
            this.m_content = this.m_content.Replace(before, after);
        }

        public void SetVar(string key, string keyvalue)
        {
            if (this.hs.ContainsKey(key))
            {
                this.hs.Remove(key);
            }
            this.hs.Add(key, keyvalue);
        }

        public string Content
        {
            get
            {
                StringBuilder builder = new StringBuilder(this.m_content);
                IDictionaryEnumerator enumerator = this.hs.GetEnumerator();
                string key = null;
                while (enumerator.MoveNext())
                {
                    key = (string) enumerator.Key;
                    builder = builder.Replace("$" + key + "$", this.hs[key].ToString());
                }
                return builder.ToString();
            }
        }

        public StringBuilder SBContent
        {
            get
            {
                StringBuilder builder = new StringBuilder(this.m_content);
                IDictionaryEnumerator enumerator = this.hs.GetEnumerator();
                string key = null;
                while (enumerator.MoveNext())
                {
                    key = (string) enumerator.Key;
                    builder = builder.Replace("$" + key + "$", this.hs[key].ToString());
                }
                return builder;
            }
        }
    }
}

